
import logging
import re

from UiManager.utils.operation import operation_project_data, operation_page_data, operation_element_data, \
    operation_suite_data, operation_env_data, operation_resource_data, operation_case_data, operation_system_data
from djcelery.models import PeriodicTask
from UiManager.utils.task_opt import create_task, edit_task, delete_task

logger = logging.getLogger('Alpaca')


def project_info_logic(type, **kwargs):
    """
    项目信息逻辑处理
    :param type: 处理类型
    :param kwargs: dict: 项目信息
    :return:
    """
    if kwargs.get('project_name') is '':
        return '项目名称不能为空'

    return operation_project_data(type, **kwargs)


def page_info_logic(type, **kwargs):
    """
    页面信息逻辑处理
    :param kwargs: dict: 页面信息
    :return:
    """
    if kwargs.get('page_name') is '':
        return '页面名称不能为空'
    if kwargs.get('belong_project') is '':
        return '所属项目不能为空'

    return operation_page_data(type, **kwargs)


def element_info_logic(type, **kwargs):
    """
    元素信息逻辑处理
    :param kwargs: dict: 元素信息
    :return:
    """
    if kwargs.get('element_name') is '':
        return '元素名称不能为空'
    if kwargs.get('belong_page') is '' or kwargs.get('belong_page') == 'none':
        return '所属页面不能为空'
    if kwargs.get('belong_location') is '':
        return '元素类型不能为空'
    if kwargs.get('element_value') is '':
        return '元素文本不能为空'

    return operation_element_data(type, **kwargs)


def case_info_logic(type, **kwargs):
    """
    用例信息逻辑处理
    :param kwargs: dict: 用例信息
    :return:
    """
    if kwargs.get('case_name') is '':
        return '用例名称不能为空'
    if len(kwargs.get('steps')) < 1:
        return '步骤不能为空'

    return operation_case_data(type, **kwargs)


def suite_info_logic(type, **kwargs):
    """
    套件信息逻辑处理
    :param kwargs: dict: 元素信息
    :return:
    """
    if kwargs.get('suite_name') is '':
        return '套件名称不能为空'
    if kwargs.get('project') is '' or kwargs.get('project') == 'none':
        return '所属项目不能为空'
    if len(kwargs.get('cases')) == 0:
        return '请选择至少一条用例'

    return operation_suite_data(type, **kwargs)


def env_info_logic(type, **kwargs):
    """
    环境信息逻辑处理
    :param kwargs: dict: 环境信息
    :return:
    """
    if kwargs.get('env_name') is '':
        return '环境名称不能为空'
    if kwargs.get('base_url') is '':
        return '环境主机不能为空'
    if kwargs.get('appPackage') is '':
        return 'appPackage不能为空'
    if kwargs.get('appActivity') is '':
        return 'appActivity不能为空'
    if kwargs.get('resource_name') is '':
        return 'apk包不能为空'
    print('$$$$$$$$$$$$$$$$$$$$$$')
    print(kwargs)
    return operation_env_data(type, **kwargs)


def resource_info_logic(type, **kwargs):
    """
    apk信息逻辑处理
    :param kwargs: dict: apk信息
    :return:
    """
    if kwargs.get('resource') is '':
        return 'resource文件不能为空'

    return operation_resource_data(type, **kwargs)


def task_logic(type, **kwargs):
    """
    定时任务逻辑处理
    :param kwargs: dict: 定时任务数据
    :return:
    """
    if type == 'delete':
        id = kwargs.pop('id')
        return delete_task(id=id)

    if kwargs.get('task_name') is '':
        return '任务名称不可为空'
    elif kwargs.get('env') == 'none':
        return '请选择一个环境'
    elif kwargs.get('suite') == 'none':
        return '请选择一个套件'
    elif kwargs.get('crontab') is '':
        return '定时配置不可为空'

    try:
        crontab_time = kwargs.pop('crontab').split(' ')
        if len(crontab_time) > 5:
            return '定时配置参数格式不正确'
        crontab = {
            'day_of_week': crontab_time[-1],
            'month_of_year': crontab_time[3],  # 月份
            'day_of_month': crontab_time[2],  # 日期
            'hour': crontab_time[1],  # 小时
            'minute': crontab_time[0],  # 分钟
        }
    except Exception:
        return '定时配置参数格式不正确'
    if PeriodicTask.objects.filter(name__exact=kwargs.get('name')).count() > 0:
        return '任务名称重复，请重新命名'
    desc = " ".join(str(i) for i in crontab_time)

    name = kwargs.pop('task_name', None)
    if type == 'add':
        return create_task(name, 'UiManager.tasks.suite_delay_run', kwargs, crontab, desc)
    elif type == 'edit_save':
        return edit_task(name, kwargs, crontab, desc)


def system_info_logic(**kwargs):
    """
    系统设置信息逻辑处理
    :param kwargs: dict: 系统设置信息
    :return: success
    """

    if kwargs.get('main_dir') is '':
        return 'appium启动文件main.js不能为空'

    if kwargs.get('resource_dir') is '':
        return '资源存放路径不能为空'

    if kwargs.get('log_dir') is '':
        return '日志存放路径不能为空'

    if kwargs.get('image_dir') is '':
        return '脚本运行生成图片存放路径不能为空'

    if kwargs.get('email_user') is '':
        return '测试报告发送邮箱不能空'

    if kwargs.get('email_password') is '':
        return '邮箱密码不能为空'

    if kwargs.get('server') is '':
        kwargs.pop('server')

    if kwargs.get('rabbitMq_url') is '':
        kwargs.pop('rabbitMq_url')

    return operation_system_data(**kwargs)


def get_ajax_msg(message):
    """
    ajax提示信息
    :param message: str：msg
    :return:res dic
    """
    res = {'code': 0, 'message': "success"}
    if message != 'success':
        res['code'] = -1
        res['message'] = message
    return res


def hooks(input_data, driver):
    input_data = input_data.strip()
    input_data = input_data.lstrip('$').split("(")
    fun = input_data[0]
    if len(input_data) == 2 and input_data[1] != ")":
        param = input_data[1].rstrip(")").strip('"').strip("'")
    else:
        param = None

    try:
        app = __import__("UiManager.debugtalk")
        debugtalk = getattr(app, 'debugtalk')
        fun = getattr(debugtalk, fun)

        # 执行view.py中的函数，并获取其返回值
        if fun.__name__ == 'enterText':
            print('传值向下')
            result = fun(param, driver)
        else:
            result = fun(param) if param else fun()

    except (ImportError, AttributeError):
        raise Exception("hooks方法名不存在")
    return result
